package com.ujiuye.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ujiuye.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@WebServlet("/jacksonDemo")
public class JacksonParseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //创建一个javaBean对象
        User u=new User(18,"李湘");
        //创建集合对象
        List<User>list=new ArrayList<>();
        list.add(new User(28,"李猪"));
        list.add(new User(60,"李传奇"));
        list.add(new User(58,"李八戒"));
        //创建Map
        Map<String,User>map=new HashMap<String,User>();
        map.put("u1",new User(28,"李猪"));
        map.put("u1",new User(60,"李传奇"));
        map.put("u1",new User(58,"李八戒"));
        //开始解析
        ObjectMapper om = new ObjectMapper();//创建json解析器
        // String json = om.writeValueAsString(u);//将对象转换为json格式字符串
        //String json = om.writeValueAsString(list);
        String json = om.writeValueAsString(map);
        System.out.println(json);
        //将解析后的数据响应给浏览器
        resp.getWriter().println(json);
    }
}
